<template>
  <div class="app-container">
    <search-table-pagination :loading="loading" :data="list" :columns="columns" :close-on-click-modal="false" :form-options="formOptions" :url="api.admin_friendlink" method="get" type="local">
      <el-button
        slot="btn"
        type="danger"
        plain
        icon="el-icon-plus"
        @click="handleCreate()"
      >
        {{ $t('btn.create') }}
      </el-button>
      <el-table-column
        slot="prepend"
        :label="$t('table.logo')"
        align="center">
        <template slot-scope="scope">
          <span><img :src="scope.row.logo" preview height="50"></span>
        </template>
      </el-table-column>
      <el-table-column
        slot="append"
        :label="$t('table.edit')"
        fixed="right"
        align="center"
        width="160">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click.native.prevent="handleEdit(scope.row)">
            {{ $t('table.edit') }}
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click.native.prevent="handleDel(scope.row, scope.$index)">
            {{ $t('btn.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </search-table-pagination>
    <el-dialog :title="isCreate ? $t('tips.add'): $t('table.edit')" :visible.sync="dialogFormVisible" :before-close="closeDialog">
      <el-form ref="dataForm" :model="formData" :rules="rules" label-width="120px">
        <el-form-item :label="$t('table.title')" prop="title">
          <el-input v-model="formData.title"/>
        </el-form-item>
        </el-form-item>
        <el-form-item :label="$t('table.logo')" prop="logo">
          <img-upload :remoteImage="formData.logo" action="friendlink" @uploadImgData="e=>{formData.logo = e}" />
        </el-form-item>
        <el-form-item :label="$t('table.url')" prop="url">
          <el-input v-model="formData.url"/>
        </el-form-item>
        <el-form-item :label="$t('table.target')" prop="target" >
          <el-radio-group v-model="formData.target">
            <el-radio :label="1">_blank</el-radio>
            <el-radio :label="2">_self</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('table.sort')" prop="sort">
          <el-input-number v-model="formData.sort" :min="1" :max="999" controls-position="right"/>
        </el-form-item>
        <el-form-item :label="$t('table.status')" prop="status">
          <el-switch v-model="formData.status" :active-value="1" :inactive-value="0"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">{{ $t('btn.cancel') }}</el-button>
        <el-button v-if="isCreate" type="primary" @click="createData">{{ $t('btn.confirm') }}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t('btn.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Http from '@/utils/http'
import ImgUpload from '@/components/Upload/ImgUpload'
import { statusSelect } from '@/utils/data'

export default {
  name: '',
  components: {
    ImgUpload
  },
  data() {
    const dialogData = {
      title: undefined,
      logo: undefined,
      target: '_blank',
      sort: 50,
      status: 1
    }
    return {
      list: {},
      loading: false,
      dialogFormVisible: false,
      isCreate: false,
      rules: undefined,
      columnData: {},
      categoryData: {},
      formData: dialogData,
      resetData: dialogData
    }
  },
  computed: {
    formOptions() {
      return {
        btnMd: 12,
        showResetBtn: true,
        forms: [
          { prop: 'title', md: 12, label: 'table.title' },
          { prop: 'status', md: 12, label: 'table.status', itemType: 'select', options: statusSelect }
        ]
      }
    },
    columns() {
      return [
        { prop: 'title', minWidth: 150, label: this.$t('table.title') },
        { prop: 'url', minWidth: 150, label: this.$t('table.url') },
        { prop: 'target', minWidth: 150, label: this.$t('table.target') },
        { prop: 'sort', minWidth: 80, label: this.$t('table.sort') },
        { prop: 'status', minWidth: 80, label: this.$t('table.status'), filter: 'statusFmt' },
        { prop: 'updated_at', minWidth: 150, label: this.$t('table.updated_at'), filter: 'parseTime|{y}-{m}-{d} {h}:{i}:{s},--' },
        { prop: 'created_at', minWidth: 150, label: this.$t('table.created_at'), filter: 'parseTime|{y}-{m}-{d} {h}:{i}:{s},--' }
      ]
    }
  },
  watch: {
    formData: {
      handler: function(val) {
        if (val.time && val.time[0]) {
          val.start_at = (val.time[0].getTime() + val.time[0].getTimezoneOffset() * 60 * 1000) / 1000
        }
        if (val.time && val.time[1]) {
          val.end_at = (val.time[1].getTime() + val.time[1].getTimezoneOffset() * 60 * 1000) / 1000
        }
      },
      deep: true
    }
  },
  created() {
  },
  mounted() {
    this.setRules()
  },
  methods: {
    setRules() {
      this.rules = {
        title: [{ required: true, message: this.$t('rules.title') }],
        logo: [{ required: true, message: this.$t('placeholder.select') }],
        url: [{ required: true, message: this.$t('placeholder.input') }]
      }
    },
    async fetchData() {
      this.loading = true
      const res = await Http.get(this.api.admin_friendlink, { page: 1, limit: 20 })
      this.list = res
      this.loading = false
    },
    async handleEdit(row) {
      this.formData = Object.assign({}, row, {logo: row.logo})
      this.dialogFormVisible = true
    },
    async handleCreate() {
      this.isCreate = true
      this.dialogFormVisible = true
    },
    handleDel(row, i) {
      this.$confirm(this.$t('tips.deleteConfirm'))
        .then(_ => {
          var url = this.api.admin_friendlink + '/' + row.id
          this.submitData(url, 'delete', this.$t('tips.delete'), { id: row.id }, i)
        })
        .catch(_ => _)
    },
    closeDialog() {
      this.formData = Object.assign({}, this.resetData)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.dialogFormVisible = false
      this.isCreate = false
    },
    updateData() {
      const FORMDATA = Object.assign({}, this.formData)
      delete (FORMDATA['id'])
      var url = this.api.admin_friendlink + '/' + this.formData.id
      this.submitData(url, 'put', this.$t('tips.update'), FORMDATA)
    },
    createData() {
      const FORMDATA = Object.assign({}, this.formData)
      this.submitData(this.api.admin_friendlink, 'post', this.$t('tips.add'), FORMDATA)
    },
    submitData(url, method, msg, param, i) {
      this.submitDataBefore(method !== 'delete', _ => {
        Http.request(url, method, param || this.formData).then(res => {
          this.$notify({
            title: this.$t('tips.success'),
            message: msg + ' ' + this.$t('tips.success'),
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        })
        i ? '' : this.closeDialog()
      })
    },
    submitDataBefore(isCheck, cb) {
      isCheck ? this.$refs.dataForm.validate(_ => _ && cb()) : cb()
    }
  }
}
</script>
